package com.dai.train.gateway.filter;

import com.dai.train.gateway.util.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

public class MemberLoginFilter implements Ordered, GlobalFilter {

    Logger LOG = LoggerFactory.getLogger(MemberLoginFilter.class);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取请求路径
        String path = exchange.getRequest().getURI().getPath();
        // 放行无需登陆的请求路径
        if(path.contains("/admin") || path.contains("/member/member/login") || path.contains("/member/member/send-code")){
            LOG.info("不需要登录验证：{}",path);
            return chain.filter(exchange);
        }

        // 校验 token
        HttpHeaders headers = exchange.getRequest().getHeaders();
        String token = headers.getFirst("token");
        if(token == null || token.isEmpty()){
            LOG.info("token 为空，请求被拦截");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

        // 使用 jwt 进行校验
        if(!JwtUtil.validate(token)){
            LOG.info("token 校验失败，请求被拦截");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

        LOG.info("token有效，放行该请求");
        return chain.filter(exchange);


    }

    @Override
    public int getOrder() {
        return 0;
    }
}
